import json

from django.http import HttpResponse
# Create your views here.
from rest_framework.views import APIView
from rest_framework.versioning import QueryParameterVersioning,URLPathVersioning

# 版本控制
# class ParamVersion(object):
#     def determine_version(self,request,*args,**kwargs):
#         version = request.query_params.get('version')
#         return version
from apitest2.models import Computer, VlanManageInfo, IpAddressUseInfo
from apitest2.serializer import VlanSerializer, ComputerSerializer, IpSerializer


class UsersView(APIView):
    authentication_classes = []
    # 在url最后?version使用QueryParameterVersioning获取版本
    # versioning_class = QueryParameterVersioning
    versioning_class = URLPathVersioning
    def get(self,request,*args,**kwargs):
        print(request.version)
        return HttpResponse('用户列表')


# 1、请求头content_type == 'application/x-www-form-urlencoded'
# 2、数据格式 name=alex&age=18&gender=男
class Django(APIView):
    authentication_classes = []
    def post(self,request,*args,**kwargs):
        print(request._request)
        print(type(request._request))
        from django.core.handlers.wsgi import WSGIRequest
        return HttpResponse('用户列表')

from rest_framework.parsers import JSONParser,FormParser

class ParseView(APIView):
    authentication_classes = []
    parser_classes = [JSONParser,FormParser,]
    def post(self,request,*args,**kwargs):
        BodyView = request.data
        print(BodyView)
        return HttpResponse('ParseView')


import json
class VlanrView(APIView):
    authentication_classes = []
    # parser_classes = [JSONParser,FormParser,]
    def get(self,request,*args,**kwargs):
        vlan = VlanManageInfo.objects.all()
        # queryset需要改成list类型
        # computer = list(vlan)
        ser = VlanSerializer(instance=vlan,many=True)
        ret = json.dumps(ser.data)
        return HttpResponse(ret)

class ComputerView(APIView):
    authentication_classes = []
    def get(self,request,*args,**kwargs):
        computer = Computer.objects.all()
        ser = ComputerSerializer(instance=computer,many=True,context={'request':request})
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)

class IpUrlView(APIView):
    authentication_classes = []
    def get(self,request,*args,**kwargs):
        pk = kwargs.get('pk')
        ip = IpAddressUseInfo.objects.filter(pk=pk).first()
        ser = IpSerializer(instance=ip,many=False)
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)

class VlanView(APIView):
    authentication_classes = []
    def get(self,request,*args,**kwargs):
        print(*args)
        print(**kwargs)
        pk = kwargs.get('pk')
        vlan = VlanManageInfo.objects.filter(pk=pk).first()
        ser = ComputerSerializer(instance=ip,many=False)
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)